//
//  AllPurchasesHistoryTableViewController.m
//  消费100
//
//  Created by eliot on 16/3/31.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "AllPurchasesHistoryTableViewController.h"
#import "TeamTableViewCell.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"

@interface AllPurchasesHistoryTableViewController ()

@property (nonatomic, strong)NSMutableArray *dataArr;

@end

@implementation AllPurchasesHistoryTableViewController

static int page = 1;

-(NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}



- (void)dealloc {
    page = 1;
}


+(AllPurchasesHistoryTableViewController*)CreatAllPurchasesHistoryTableViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    AllPurchasesHistoryTableViewController *AllPurchasesHistoryTableViewController=[story instantiateViewControllerWithIdentifier:@"AllPurchasesHistoryTableViewController"];
    return AllPurchasesHistoryTableViewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /** 注册*/
    [self.tableView registerNib:[UINib nibWithNibName:@"TeamTableViewCell" bundle:nil] forCellReuseIdentifier:@"TeamTableViewCell"];
    self.title = @"所有众购记录";
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = [UIColor colorWithRed:232/255.0 green:233/255.0 blue:232/255.0 alpha:1];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"PurchasesTableViewCell" bundle:nil] forCellReuseIdentifier:@"PurchasesTableViewCell"];
    MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = footer;
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":@"1", @"crowdfundingId":self.productId};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getCrowdfundingOrde.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{

            self.dataArr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    
}


- (void)loadMoreData {
    
    page += 1;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
     NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d",page], @"crowdfundingId":self.productId};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getCrowdfundingOrde.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView.mj_footer endRefreshing];
            [self.dataArr addObjectsFromArray:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
            
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//    if ( !cell) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
//    }
    tableView.showsVerticalScrollIndicator = NO;
    TeamTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TeamTableViewCell" forIndexPath:indexPath];
    NSDictionary *dic = self.dataArr[indexPath.row];
    [cell.iconIV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", dic[@"consumerImg"]]]];
    cell.nameLb.text = dic[@"consumerPhone"];
    
    // 时间戳转时间的方法:
    long sendTime1 = [dic[@"inDate"][@"time"] longValue];
    sendTime1 = sendTime1 / 1000;
    NSDate *date1 = [AllPurchasesHistoryTableViewController timeFormatted:sendTime1];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //用[NSDate date]可以获取系统当前时间
    NSString *timeSt1 = [dateFormatter stringFromDate:date1];
    timeSt1 = [timeSt1 stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
    
    
    cell.phoneNumLb.text = [NSString stringWithFormat:@"众购%@金币 %@", dic[@"coin"], timeSt1];
    cell.iconIVW.constant = 52 / 320.0 *Width;
    cell.iconIVH.constant = 52 / 320.0 *Width;
    cell.nameLbTop.constant = 20 / 320.0 *Width;
    
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (Width <= 320) {
        return 78 / 320.0 *Width;
    }else {
        return 78 / 320.0 *Width + 4;
    }
}

    /** 时间处理*/
                            + (NSDate *)timeFormatted:(long)totalSeconds
    {
        
        
        NSDate  *date = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMTForDate: date];
        NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
        return localeDate;
    }

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
